<template>
  <div class="warpper-box">
    <enterprise-select v-if="userInfo.type == 4" ref="enterprise" @enterpriseChange="enterpriseChange"></enterprise-select>
    <a-card style="margin-top: 10px;">
      <a-form layout="inline">
        <a-form-item label="参保人员">
          <a-input placeholder="请输入参保人员" v-model="params.insureName"></a-input>
        </a-form-item>
        <a-form-item label="证件号码">
          <a-input placeholder="请输入证件号码" v-model="params.idCard"></a-input>
        </a-form-item>
        <a-form-item label="参保城市">
          <a-cascader :options="cityJson" placeholder="请选择" v-model="city" @change="cityChange"/>
        </a-form-item>
				<a-form-item label="参保状态">
				  <a-select style="width: 200px" v-model="params.insureStatus" placeholder="请选择参保方案">
				    <a-select-option :key="1" :value="1">未参保</a-select-option>
						<a-select-option :key="2" :value="2">已参保</a-select-option>
				  </a-select>
				</a-form-item>
        <a-form-item label="参保方案">
          <a-select style="width: 200px" v-model="params.caseId" placeholder="请选择参保方案">
            <a-select-option :key="item.caseId" :value="item.caseId" v-for="item in planData">{{ item.caseName }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" icon="search" @click="loadTable(true)">搜索</a-button>
          <a-button type="primary" icon="setting" @click="reset()">重置</a-button>
          <a-button type="primary" @click="joinStaffExport">导出</a-button>
          
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="importJoinVisible = true">批量添加参保人员</a-button>
          <a-button type="warning" @click="importStopVisible = true">批量添加停保人员</a-button>
					<a-button type="primary" ghost :disabled="this.selectedRowKeys.length == 0" @click="batchHandle(2)">批量参保增员</a-button>
					<a-button type="primary" ghost :disabled="this.selectedRowKeys.length == 0" @click="batchHandle(1)">批量参保减员</a-button>
          <!-- <a-button type="primary" icon="plus" @click="openAdd">添加参保人员</a-button> -->
          <!-- <a-button type="primary" @click="importBaseVisible = true">导入基数</a-button> -->
          <!-- <a-button type="primary" :disabled="this.selectedRowKeys.length == 0" @click="$refs.createInfo.add(true, selectedRowKeys)">一键调基</a-button> -->
        </a-form-item>
      </a-form>
      <a-table :columns="table.columns" :data-source="table.loadData" :pagination="table.pagination" @change="handleTableChange" rowKey="insureNo" :scroll="{ x: 2800 }" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <span slot="insurePayStatus" slot-scope="text">
          <span v-if="text == 1" style="color: #04D919;">在缴</span>
          <span v-else style="color: #D9001B;">停缴</span>
        </span>
        <!-- 操作栏-->
        <span slot="action" slot-scope="text, record">
          <!-- 编辑模块 | 字段 -->
          <!-- <a @click="$refs.createInfo.add(record, planData)">修改基数</a>
          <a-divider type="vertical" v-show="record.insureStatus == 1"/> -->
          <a-popconfirm v-show="record.insureStatus == 1" title="是否增加参保人员？" ok-text="确认" cancel-text="取消" @confirm="addStaff(record)">
            <a>参保增员</a>
          </a-popconfirm>
          <a-popconfirm v-show="record.insureStatus == 2" title="是否减除参保人员？" ok-text="确认" cancel-text="取消" @confirm="reduceStaff(record)">
            <a>参保减员</a>
          </a-popconfirm>
          <a-divider type="vertical" />
          <a @click="stopStaff(record)">停缴设置</a>
          <a-divider type="vertical" />
          <a @click="staffDetail(record)">参保详情</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确认移除?" ok-text="确认" cancel-text="取消" @confirm="remove(record)">
            <a>移除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </a-card>
    <add-info ref="createInfo" @on-ok="addLoad"></add-info>
    <!-- 添加参保人员 -->
    <!-- <a-modal v-model="isAdd" title="选择员工" :confirmLoading="submitLoadingAdd" width="400px" ok-text="确认" cancel-text="取消" @ok="addSubmit">
      <a-select style="width: 280px" v-model="caseId" placeholder="请选择参保方案">
        <a-select-option :key="item.caseId" :value="item.caseId" v-for="item in planData">{{ item.caseName }}</a-select-option>
      </a-select>
      <a-tree v-if="treeData.length > 0" v-model="checkedKeys" :tree-data="treeData" :defaultExpandedKeys="expandedKeys" :replaceFields="{ title: 'orgName', key: 'orgId' }" checkable>
      </a-tree>
    </a-modal> -->
    <!-- 停缴设置 -->
    <a-modal v-model="isStop" title="停缴设置" :confirmLoading="submitLoadingStop" width="500px" ok-text="确认" cancel-text="取消" @ok="stopSubmit">
      <a-space style="padding-left: 80px;">
        社保公积金停缴：
        <a-radio-group v-model="insurePayStatus">
          <a-radio :value="1">
            在缴
          </a-radio>
          <a-radio :value="2">
            停缴
          </a-radio>
        </a-radio-group>
      </a-space>
      <!-- <a-space style="padding-left: 24px;padding-top: 10px;">
        停缴开始月份：
        <a-month-picker valueFormat="YYYY-MM" v-model="insureMonth" placeholder="选择月份"></a-month-picker>
      </a-space> -->
    </a-modal>
    <!-- 导入基数 -->
    <!-- <a-modal v-model="importBaseVisible" title="导入基数" width="540px" :footer="null">
      <a-alert message="第一步：下载基数录入模板；模版内已包含最新员工信息，请点击下载。" type="info" />
      <a-button type="primary" @click="downloadBase" ghost style=";margin: 20px 0;width: 160px;">下载模板</a-button>
      <a-alert message="第二步：批量导入基数数据；请将填写完整的员工社保基数。" type="info" />
      <a-button type="primary" @click="importBase" style="margin: 20px 0;width: 160px;">上传文件</a-button>
      <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileBaseExcel"
        @change="importBaseHandle" style="display: none;" />
    </a-modal> -->
    <!-- 批量导入参保人员 -->
    <a-modal v-model="importJoinVisible" title="参保人员导入" width="540px" :footer="null">
      <a-alert message="第一步：下载参保人员录入模板；模版内已包含最新员工信息，请点击下载。" type="info" />
      <a-button type="primary" @click="downloadJoin" ghost style=";margin: 20px 0;width: 160px;">下载模板</a-button>
      <a-alert message="第二步：批量导入参保人员数据；请将填写完整的员工社保基数。" type="info" />
      <a-button type="primary" @click="importJoin" style="margin: 20px 0;width: 160px;">上传文件</a-button>
      <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileJoinExcel"
        @change="importJoinHandle" style="display: none;" />
    </a-modal>
    <!-- 批量导入停保人员 -->
    <a-modal v-model="importStopVisible" title="停保人员导入" width="540px" :footer="null">
      <a-alert message="第一步：下载停保人员录入模板；模版内已包含最新员工信息，请点击下载。" type="info" />
      <a-button type="primary" @click="downloadStop" ghost style=";margin: 20px 0;width: 160px;">下载模板</a-button>
      <a-alert message="第二步：批量导入停保人员数据；请将填写完整的员工社保基数。" type="info" />
      <a-button type="primary" @click="importStop" style="margin: 20px 0;width: 160px;">上传文件</a-button>
      <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileStopExcel"
        @change="importStopHandle" style="display: none;" />
    </a-modal>
  </div>
</template>

<script>
import store from '@/store'
import EnterpriseSelect from "@/components/human/enterpriseSelect.vue"
import {
  COLUMNS_JOINSTAFF
} from "./form"
import {
  OPTION_BLOCK,
  OPTION_INLINE
} from "../base_form"
import {
  cityJson
} from "@/api/human/city.js"
import AddInfo from "./joinStaff_add"
import {
  getTablePage,
  exportInsureStaffInfo,
  selectEnterpriseOrgTreeStaff,
  listInsureCase,
  listInsureStaffSelected,
  addInsureStaff,
  downloadInsureBaseExcelTemplate,
  importInsureBase,
  joinInsure,
  deleteInsureStaff,
  updateInsurePayStatus,
  importInsurePayStatus,
  downloadInsureStopExcelTemplate,
	joinInsureBatch
} from "@/api/human/ensureJoinStaff"
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'joinStaff',
  components: {
    AddInfo,
    EnterpriseSelect
  },
  data() {
    return {
      params: {
        insureName: "",
        idCard: "",
        caseId: undefined,
        city: "",
      },
      city: [],
      cityJson: cityJson,
      table: {
        columns: COLUMNS_JOINSTAFF,
        loadData: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      pagination: { current: 1, pageSize: 10 },

      enterpriseId: "", // 企业id
      enterpriseData: [], // 客户列表

      submitLoadingStop: false,
      isStop: false, // 停缴设置开关
      insureNo: "",
      insurePayStatus: 1,
      submitLoadingAdd: false,
      isAdd: false, // 添加参保人员开关
      caseId: undefined, // 参保方案id
      planData: [], // 方案列表
      treeData: [], // 人员列表
      checkedKeys: [],
      expandedKeys: [],
      importBaseVisible: false, // 导入基数开关
      importJoinVisible: false, // 导入参保开关
      importStopVisible: false, // 导入停保开关

      selectedRowKeys: [], // 选择的table数据id
      selectedRows: [], // 选择的table数据
    }
  },
  filters: {
    
  },
  mounted() {
    window.addEventListener('keyup', this.keyDown);
    if (this.userInfo.type == 4) {
      this.$refs.enterprise.getEnterpriseData();
    } else {
      this.enterpriseId = this.userInfo.relationId
      this.loadTable(true);
      this.getPlanData();
    }
  },
  destroyed() {
    window.removeEventListener('keyup', this.keyDown);
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    })
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {

  },
  methods: {
		// 批量操作
		async batchHandle(status) {
			const { code, data } = await joinInsureBatch({
				insureNoList: this.selectedRowKeys,
				insureStatus: status
			});
			if (code === '1') {
			  this.$message.success('操作成功');
			  this.addLoad();
			}
		},
    // table复选框选择
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 获取列表
    async loadTable(flag) {
      let params = this.params;
      if (flag) {
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      if (this.city.length > 0) {
        this.city.pop();
        params.city = this.city.join(',');
      }
      params.enterpriseId = this.enterpriseId;
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const { code, data } = await getTablePage(params);
      if (code === '1') {
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
      }
    },
    handleTableChange(pagination) {
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    // 导出
    joinStaffExport() {
      this.params.enterpriseId = this.enterpriseId;
      exportInsureStaffInfo(this.params).then(res => {
        const blob = new Blob([res]);
        const fileName = '参保人员.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 基数下载模板
    downloadBase() {
      downloadInsureBaseExcelTemplate({enterpriseId: this.enterpriseId}).then(res => {
        const blob = new Blob([res]);
        const fileName = '基数录入模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 导入基数表单
    importBase() {
      this.$refs.fileBaseExcel.click();
    },
    importBaseHandle(e) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) {
        return;
      }
      if (file.name.indexOf('.xls') === -1) {
        _this.$message.error("只支持xlsx");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 20)) {
        _this.$message.error('模版大小不能超过 20MB!');
        e.target.value = "";
        return;
      }
      e.target.value = "";
      if (file) {
        let formData = new FormData();
        formData.append("enterpriseId", _this.enterpriseId);
        formData.append("file", file);
        importInsureBase(formData).then((res) => {
          if (res.code == 1) {
            _this.importBaseVisible = false;
            _this.$message.success('操作成功');
            _this.loadTable(true);
          }
        })
      }
    },
    // 参保人员下载模板
    downloadJoin() {
      downloadInsureBaseExcelTemplate({enterpriseId: this.enterpriseId}).then(res => {
        const blob = new Blob([res]);
        const fileName = '参保人员录入模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 导入基数表单
    importJoin() {
      this.$refs.fileJoinExcel.click();
    },
    importJoinHandle(e) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) {
        return;
      }
      if (file.name.indexOf('.xls') === -1) {
        _this.$message.error("只支持xlsx");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 20)) {
        _this.$message.error('模版大小不能超过 20MB!');
        e.target.value = "";
        return;
      }
      e.target.value = "";
      if (file) {
        let formData = new FormData();
        formData.append("enterpriseId", _this.enterpriseId);
        formData.append("file", file);
        importInsureBase(formData).then((res) => {
          if (res.code == 1) {
            _this.importJoinVisible = false;
            _this.$message.success('操作成功');
            _this.loadTable(true);
          }
        })
      }
    },
    // 停保人员下载模板
    downloadStop() {
      downloadInsureStopExcelTemplate({enterpriseId: this.enterpriseId}).then(res => {
        const blob = new Blob([res]);
        const fileName = '停保人员录入模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 批量导入停保人员
    importStop() {
      this.$refs.fileStopExcel.click();
    },
    importStopHandle(e) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) {
        return;
      }
      if (file.name.indexOf('.xls') === -1) {
        _this.$message.error("只支持xlsx");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 20)) {
        _this.$message.error('模版大小不能超过 20MB!');
        e.target.value = "";
        return;
      }
      e.target.value = "";
      if (file) {
        let formData = new FormData();
        formData.append("enterpriseId", _this.enterpriseId);
        formData.append("file", file);
        importInsurePayStatus(formData).then((res) => {
          if (res.code == 1) {
            _this.importStopVisible = false;
            _this.$message.success('操作成功');
            _this.loadTable(true);
          }
        })
      }
    },
    // 跳转员工详情
    staffDetail(row) {
      this.$router.push({ name: 'humanResourcesRelationStaffInfoCode', query: { 
        enterpriseId: this.enterpriseId,
        idCard: row.idCard,
        type: "2"
      }});
    },
    // 参保增员
    async addStaff(row) {
      let params = {
        insureNo: row.insureNo,
        insureStatus: 2
      }
      const { code } = await joinInsure(params)
      if (code == 1) {
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    // 参保减员
    async reduceStaff(row) {
      let params = {
        insureNo: row.insureNo,
        insureStatus: 1
      }
      const { code } = await joinInsure(params)
      if (code == 1) {
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    // 移除参保人员
    async remove(row) {
      let params = {
        insureNo: row.insureNo,
      }
      const { code } = await deleteInsureStaff(params)
      if (code == 1) {
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    // 打开添加参保人员
    openAdd() {
      this.isAdd = true;
      this.caseId = undefined;
      this.treeData = [];
      this.checkedKeys = [];
      this.expandedKeys = [];
      this.getStaffInfo();
    },
    // 获取已添加员工编号
    async getStaffInfo() {
      const { code, data } = await listInsureStaffSelected({enterpriseId: this.enterpriseId});
      if (code === '1') {
        this.checkedKeys = data;
        this.expandedKeys = data;
        this.getTreeData();
      }
    },
    // 获取人员列表
    async getTreeData() {
      let params = {
        parentOrgId: this.enterpriseId,
        enterpriseId: this.enterpriseId,
        staffType: 1
      }
      const { code, data } = await selectEnterpriseOrgTreeStaff(params);
      if (code === '1') {
        this.treeData = data;
      }
    },
    // 获取方案列表
    async getPlanData() {
      const { code, data } = await listInsureCase(this.enterpriseId);
      if (code === '1') {
        this.planData = data;
      }
    },
    // 添加参保人员提交
    async addSubmit() {
      if (!this.caseId) {
        return this.$message.warning('请选择参保方案')
      }
      if (this.checkedKeys.length == 0) {
        return this.$message.warning('请选择参保人员')
      }
      let params = {
        enterpriseId: this.enterpriseId,
        caseId: this.caseId,
        staffList: this.checkedKeys
      }
      this.submitLoadingAdd = true;
      const { code } = await addInsureStaff(params)
      this.submitLoadingAdd = false;
      if (code == 1) {
        this.isAdd = false;
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    // 停缴开关
    stopStaff(row) {
      this.isStop = true;
      this.insureNo = row.insureNo;
      this.insurePayStatus = row.insurePayStatus;
    },
    // 停缴设置提交
    async stopSubmit() {
      let params = {
        insureNo: this.insureNo,
        insurePayStatus: this.insurePayStatus
      }
      this.submitLoadingStop = true;
      const { code } = await updateInsurePayStatus(params)
      this.submitLoadingStop = false;
      if (code == 1) {
        this.isStop = false;
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    // 方案配置
    planHandle(row) {
      this.$router.push({ name: 'humanResourcesEnsurePublicPlanHandleCode', query: { caseId: row.caseId } });
    },
    // 企业选择回调
    enterpriseChange(value) {
      this.enterpriseId = value;
      this.loadTable(true);
      this.getPlanData();
    },
    addLoad() {
      this.loadTable(true);
      this.selectedRowKeys = [];
      this.selectedRows = [];
    },
    cityChange(e) {
      if (e.length == 0) {
        this.params.city = "";
      }
    },
    reset() {
      this.params.insureName = "";
      this.params.idCard = "";
      this.params.caseId = undefined;
      this.params.city = "";
      this.city = [];
      this.loadTable(true);
    }
  }
}
</script>
<style lang="less"></style>